<?php

namespace haibao\cms\business\control\pc\channel\brands;

use haibao\frame\data\query\Condition;
use \haibao\cms\business\control\ArticleController as ArticleController;
use \haibao\cms\business\Brand as BrandBusiness;

class BrandsController extends \haibao\cms\business\control\pc\channel\ChannelController{
    
	public function __construct($updateTime = null,$controlId,$isPublish){
		parent::__construct($updateTime,$controlId,$isPublish);
	}
	
    public function displayTemplateHtml(){
        $controlData = $this->getParameter(self::$CONTROL_DATA);
		$content = $this->getParameter(self::$CONTROL_CONTENT);
		$path = $this->generateHtmlPath(__CLASS__);
		$designerList = array();
		/* 品牌库首页——精品栏目 */
		$brandsTagArr = $brandArticleData = $brandAreaAndPosition = $starAreaAndPosition=$starArticleData = array();
		$brandsInfo = array();
		$weekBuyInfo = array();
		$nweBrandInfo = array();
		$hotProduceList = array();
		$newProduct = array();
		if($controlData['manual'] && $controlData['manual']['contorllerType'] == 'fineColumns'){
		    if($controlData['manual']['tagId']){
		        $brandsTagArr = explode(',',$controlData['manual']['tagId']);
		    }
		    $this->getDate($brandsTagArr);
		}

		/* 品牌库首页——报友最喜爱TOP5*/
		if($controlData['manual'] && $controlData['manual']['contorllerType'] == 'brandsStop'){
		    $parameters = array();
		    if($controlData['auto']){
		        $temp = array();
		        foreach($controlData['auto'] as $data){
		            $parameterValue = json_decode($data['ParameterValue']);
		            array_push($parameters,$parameterValue);
		        }
		        array_slice($parameters, 0,$controlData['manual']['limit']);
		    }
		    
		    $brandsCount = count($parameters);
		   
		    if(($brandsCount == $controlData['manual']['limit']) || ($brandsCount == 0)){
		        $this->assign('dataList',$this->getBrandTop($parameters,$controlData['manual']['limit']));
		    }else{
		        $firstData = $this->getBrandTop($parameters,$brandsCount);
		        $secondData = $this->getBrandTop("",$controlData['manual']['limit']-$brandsCount);
		        $this->assign('dataList',array_merge($firstData,$secondData));
		    }
		    
		}
		
		/* 品牌库首页——大牌设计师*/
		if($controlData['manual'] && $controlData['manual']['contorllerType'] == 'designer'){
		    $designerList = $this->getDesigner($controlData['manual']['limit']);
		}
		$this->assign('designerList',$designerList);
		
		
		//新品上架
		if($controlData['manual'] && $controlData['manual']['contorllerType'] == 'newProduct'){
		    $newProduct = $this->getNewProductList($controlData['manual']['limit']);	//limit 改为16
		    if($newProduct){
		        foreach($newProduct as $key =>$value){
// 		            $newProduct[$key]['ProductUrl'] = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_BRANDS).'/product/'.$value['oldProductId'].'/';
		        	$newProduct[$key]['ProductUrl'] = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_BRANDS).'/product/'.$value['ProductId'].'/';
		            if(isset($value['BrandUrl'])){
		                $newProduct[$key]['BrandUrl'] = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_BRANDS).$value['BrandUrl'];
		            }else{
		                $newProduct[$key]['BrandUrl'] = "";
		            }
		            
		            if(isset($value['CategoryId'])  && !empty($value['CategoryId'])){
		            	$lastCategoryId = $value['CategoryId'];
		            	$category = isset($value['ParentId']) ? $value['ParentId'] : 0;
		            	$parentId = 0;
		            	
		            	$categoryList = \haibao\www\cache\Library::getSearchCache('ProductBanner');
		            	if($categoryList){
		            		$categoryList = json_decode($categoryList,true);
		            	}else{
		            		$categoryList = \haibao\classlibrary\cms\common\Product::getCategoryParentArr();
		            	}
		            	
		            	foreach ($categoryList as $name=>$vv){
		            		foreach ($vv['Child'] as $k=>$v){
		            			if($v['Id'] == $category){
		            				$parentId = $vv['Id'];
		            			}
		            		}
		            	}
		            	
		                $newProduct[$key]['CategoryUrl'] = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_BRANDS).'/product/list.html?parentid='.$parentId.'&category='.$category.'&lastcategory='.$lastCategoryId;
		            }else{
		                $newProduct[$key]['CategoryUrl'] = "";
		            }
		        }
		    }
		    /* 品牌库首页-热门新品 */
		        // if($controlData['auto']){
		        // 		$temp = array();
		        // 		foreach($controlData['auto'] as $data){
		        // 		      $parameterValue = json_decode($data['ParameterValue']);
		        // 		         array_push($hotProduceList,$parameterValue);
		        // 		 }
		        //}
		        if(!empty($newProduct)){
		            $hotProduceList = array();
		            foreach($newProduct as $key=>$val){
		                $hotProduceList[$val['CategoryName']] = array('CategoryName'=>$val['CategoryName'],'CategoryUrl'=>$val['CategoryUrl']);
		            }
		            if($hotProduceList){
		                $hotProduceList = array_slice($hotProduceList,0,5);
		            }
		        }
		}
		$this->assign('newProduct', $newProduct);
		$this->assign('hotProduceList', $hotProduceList);
		
		//活跃明星文章
		if($controlData['manual'] && $controlData['manual']['contorllerType'] == 'Brand'){
		    if($controlData['manual']['limit']){
		        $param['limit'] = $controlData['manual']['limit'];
		        $param['relType']=2;
		        $param['tagType']=4;
		        $param['proImageLevel'] = 5;
		        $starArticleData = $this->getStarOrBrandArticle($param);
		        if($starArticleData){
		            foreach($starArticleData as $key =>$value){
		                $starArticleData[$key]['ArticleUrl'] = $this->getArticleUrl($value['ArticleInfo'][0]['PublishId'],$value['ArticleInfo'][0]['TagId']);
		                $starArticleData[$key]['TopicUrl'] = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_STARS).$value['Url'];
		                $starArticleData[$key]['ProImage'] = $value['ArticleInfo'][0]['ProImage'];
		                $starArticleData[$key]['Title'] = $value['ArticleInfo'][0]['Title'];
		                $starArticleData[$key]['ShortTitle'] = $value['ArticleInfo'][0]['ShortTitle'];
		                $starArticleData[$key]['ArticleId'] = $value['ArticleInfo'][0]['ArticleId'];
		            }
		        }
		
		        $starAreaAndPosition = $this->getAreaAndPosition($param['tagType']);//明星所在地区，明星分类
		
		        //品牌推荐文章
		        $param['relType']=1;
		        $param['tagType']=1;
		        $param['proImageLevel'] = 4;
		        $brandArticleData = $this->getStarOrBrandArticle($param);
		        foreach($brandArticleData as $key =>$value){
		            /* 是否包含汉字 是否重名 */
		            $brandArticleData[$key]['isIncludeCn'] = $this->getIncludeCn(trim($brandArticleData[$key]['NameEn']));
		            $brandArticleData[$key]['isRepeatName'] = $this->getRepeatName(trim($brandArticleData[$key]['NameCn']),trim($brandArticleData[$key]['NameEn']));
		             
		            $brandArticleData[$key]['ArticleUrl'] = $this->getArticleUrl($value['ArticleInfo'][0]['PublishId'],$value['ArticleInfo'][0]['ParentId']);
		            // 					$brandArticleData[$key]['ArticleUrl'] = $this->getArticleUrl($value['ArticleInfo'][0]['PublishId'],$value['ArticleInfo'][0]['TagId']);
		            $brandArticleData[$key]['ProImage'] = $value['ArticleInfo'][0]['ProImage'];
		            $brandArticleData[$key]['Title'] = $value['ArticleInfo'][0]['Title'];
		            $brandArticleData[$key]['ShortTitle'] = $value['ArticleInfo'][0]['ShortTitle'];
		            $brandArticleData[$key]['ArticleId'] = $value['ArticleInfo'][0]['ArticleId'];
		            if(isset($value['Url'])){
		                $brandArticleData[$key]['TopicUrl'] = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_BRANDS).$value['Url'];
		            }else{
		                $brandArticleData[$key]['TopicUrl'] = '';
		            }
		        }
		        $brandAreaAndPosition = $this->getAreaAndPosition($param['tagType']);//品牌所在地区，明星分类
		         
		        $key = 0;
		        for($i=ord('A');$i<=ord('Z');$i++){
		            $searchArr[$key] = chr($i);
		            $key++;
		        }
		        array_push($searchArr, "其他");
		        if(count($brandArticleData) > 6){
		            $brandArticleData = array_slice($brandArticleData,0,6);
		        }
		    }
		    $isHomePage = 2;
		    $this->assign('brandsHost', \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_BRANDS));
		    $this->assign('searchArr', $searchArr);
		    $this->assign('starPosition', $starAreaAndPosition);
		    $this->assign('brandPosition', $brandAreaAndPosition);
		    $this->assign('starArticleData', $starArticleData);
		    $this->assign('brandArticleData', $brandArticleData);
		    $this->assign('brandArticleDataCount', count($brandArticleData));
		    $this->assign('isHomePage', $isHomePage);
		}
		
		$domainHost = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_STATIC_DOMAIN);
		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_CDN_DEFAULT)){
		    $domainHost = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_CDN_DOMAIN);
		}
		$exclusiveHost = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_EXCLUSIVE);
		$brandHost = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_BRANDS);
		$designerHost = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_DESIGNER);
		$wwwHost = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HAIBAO_URL);
		
		$this->assign('staticHost', $domainHost);
		$this->assign('designerHost', $designerHost);
		$this->assign('exclusiveHost', $exclusiveHost);
		$this->assign('brandHost', $brandHost);
		$this->assign('wwwHost', $wwwHost);
		$this->assign('staticVersion', \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_STATIC_VERSION));
		$this->assign('BrandsUrl', \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_BRANDS));
		$this->assign('StarsUrl', \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_STARS));
		$this->assign('DesignersUrl', \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_DESIGNER));
		$this->assign('ProductUrl', \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_BRANDS).'/product/list_0_0/');
		$this->assign('ExclusiveUrl', \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_EXCLUSIVE));
		$this->assign('PicUrl', \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_PIC));
		$this->assign('markType', ArticleController::INFO_TYPE_ARTICLE);
		$this->assign('attentionTypeStar', \haibao\www\model\data\Favorite::ATTENTION_TYPE_STAR);
		$this->assign('attentionTypeBrand', \haibao\www\model\data\Favorite::ATTENTION_TYPE_BRAND);
		$isNewHtml = $this->generateHtml($path,$content);
		$content = $this->getHtml($path);
		$content = $this->replaceCDNLink($content);
		return $content;
     }
     
     private function getNewProduct($limit){
         $articleControl = ArticleController::initArticleControl();
         return $articleControl->getNewProductAndBrand($limit);
     }
     
     private function getNewProductList($limit){
     	$articleControl = ArticleController::initArticleControl();
     	return $articleControl->getNewProductAndBrandList($limit);
     }
     
     private function getDate($brandsTagArr){
         /**
          * 品牌谍报 $brandsTagArr[0]
          * 每周必BUY $brandsTagArr[1]
          * 新品见报 $brandsTagArr[2]
          * 系列名称：serial
          * 精品栏目：ColumnId
          */
         $content = array();
         $brandsInfo = \haibao\cms\business\control\FeatureController::getBrandSerialInfoById($brandsTagArr[0],"serial",$brandsTagArr);
         $weekBuyInfo = \haibao\cms\business\control\FeatureController::getBrandSerialInfoById($brandsTagArr[1],"serial",$brandsTagArr);
         $nweBrandInfo = \haibao\cms\business\control\FeatureController::getBrandSerialInfoById($brandsTagArr[2],"serial",$brandsTagArr);
  
         $dataList = $tempUrl = array(); 
         array_push($dataList, $brandsInfo);
         array_push($dataList, $weekBuyInfo);
         array_push($dataList, $nweBrandInfo);
         if($dataList){
             foreach ($dataList as $key => $val){
                 if(isset($val->PictureId) && $val->PictureId){
                     $tempUrl['tempUrl'] = \haibao\cms\business\ImageLibrary::getImageUrlById($val->PictureId);
                     if(isset($tempUrl['tempUrl'][$val->PictureId])){
                         $val->PictureId = self::getImageLink($tempUrl['tempUrl'][$val->PictureId],340,340);
                     }
                 }
             }
         }
         $this->assign('dataList', $dataList);
         $this->assign('brandsInfo', $brandsInfo);
         $this->assign('weekBuyInfo', $weekBuyInfo);
         $this->assign('nweBrandInfo', $nweBrandInfo);
          
     }
     
     /**
      * 根据报粉获取报友最爱
      * @param array $brandIds
      * @param int $limit
      */
     private function getBrandTop($brandIds,$limit){
         $dataList = array();
         $brandIdArr = array();
         $temp = array();
         $tempUrl = array();
         if($brandIds){
             foreach ($brandIds as $value){
                 $temp = explode(',',$value->brandsinfo);
                 array_push($brandIdArr, $temp['0']);
             }
         }
         $brandFilter = new \haibao\cms\model\filter\Brand();
         $brandFilter->select(array(
             \haibao\cms\model\filter\Brand::CONDITION_FIELD_NAME_ID,
             \haibao\cms\model\filter\Brand::CONDITION_FIELD_NAME_TAG_ID,
             \haibao\cms\model\filter\Brand::CONDITION_FIELD_NAME_IMGID,
             \haibao\cms\model\filter\Brand::CONDITION_FIELD_NAME_NAMECN,
             \haibao\cms\model\filter\Brand::CONDITION_FIELD_NAME_NAMEEN,
             \haibao\cms\model\filter\Brand::CONDITION_FIELD_NAME_STATUS
         ));
         $BrandStatisticalInfoFilter = new \haibao\cms\model\filter\BrandStatisticalInfo();
         $BrandStatisticalInfoFilter->select(array(
             \haibao\cms\model\filter\BrandStatisticalInfo::CONDITION_FIELD_NAME_ID,
             \haibao\cms\model\filter\BrandStatisticalInfo::CONDITION_FIELD_NAME_BRAND_ID,
             \haibao\cms\model\filter\BrandStatisticalInfo::CONDITION_FIELD_NAME_FANS_NUM,
             \haibao\cms\model\filter\BrandStatisticalInfo::CONDITION_FIELD_NAME_EDITFANSNUM,
         ));
      
         $brandFilter->order(\haibao\cms\model\filter\BrandStatisticalInfo::CONDITION_FIELD_NAME_FANS_NUM,false,$BrandStatisticalInfoFilter);
         $brandFilter->where($brandFilter::CONDITION_FIELD_NAME_STATUS, Condition::CONDITION_EQUAL, \haibao\cms\model\data\Brand::STATUS_ENABLE);
         $brandFilter->leftJoin($BrandStatisticalInfoFilter,null,
             \haibao\cms\model\filter\Brand::CONDITION_FIELD_NAME_ID,
             \haibao\cms\model\filter\BrandStatisticalInfo::CONDITION_FIELD_NAME_BRAND_ID,
             \haibao\cms\model\filter\Brand::CONDITION_FIELD_NAME_BRAND_PIC,false);
         $brandFilter->limit($limit);
         if($brandIdArr){
             $brandFilter->where(\haibao\cms\model\filter\Brand::CONDITION_FIELD_NAME_ID, Condition::CONDITION_IN, $brandIdArr);
         }
         $brandList = \haibao\cms\business\Brand::getBrandByFilter($brandFilter);
         
         $tempTag = $getTopicIdArr = array();
         foreach ($brandList as $key => $val){
              array_push($tempTag, $val->TagId);
         }
         $getTopicIdArr = \haibao\cms\business\Tag::getTopicIdByTagId($tempTag);
       
         foreach ($brandList as $key => $val){
             $dataList[$key]['Id'] = $val->Id;
             if(isset($getTopicIdArr[$val->TagId])){
                 $dataList[$key]['topic_Id'] = $getTopicIdArr[$val->TagId];
             }else{
                 $dataList[$key]['topic_Id'] = '';
             }
             $dataList[$key]['isIncludeCn']  = $this->getIncludeCn(trim($val->NameEN)); 
             $dataList[$key]['isRepeatName'] = $this->getRepeatName(trim($val->NameCN), trim($val->NameEN));
            
             $dataList[$key]['NameCN'] = $val->NameCN;
             $dataList[$key]['NameEN'] = $val->NameEN;
             if($val->ImgId){
                 $tempUrl['tempUrl'] = \haibao\cms\business\ImageLibrary::getImageUrlById($val->ImgId);
                 $dataList[$key]['ImgUrl'] = self::getImageLink($tempUrl['tempUrl'][$val->ImgId],160,160);
             }else{
                 $dataList[$key]['ImgUrl'] = '';
             }
             if($val->BrandPic->EditFansNum){
                 $dataList[$key]['FansNum'] = '('.$val->BrandPic->EditFansNum.'个报粉)';
             }else{
                 $dataList[$key]['FansNum'] = '(0个报粉)';
             }
         }
      
         return $dataList;
     }
     
     private function getDesigner($limit){
        $designerList = $designerInfoList = $tempUrl = array();
        $designControllerData = new \haibao\cms\data\control\DesignController();
        $designerList = $designControllerData->getDesigner($limit);
        $bransdHost = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_HOST_BRANDS);
        $brandIdArr = $designerBrandArr = $brandUrlArr = array();
       
        foreach ($designerList as $bkey => $bvalue){
            if($bvalue['IsBrand'] == 0){
                if($bvalue['BrandId']){
                    array_push($brandIdArr, $bvalue['BrandId']);
                }
            }
        }
      
        if($brandIdArr){
            $designerBrandArr = \haibao\cms\business\Brand::getBrandByIds($brandIdArr);
            if($designerBrandArr){
                foreach ($designerBrandArr as $bdkey => $bdvalue){
                    $brandUrlArr[$bdkey]['BrandUrl'] = $bdvalue->BrandUrl;
                    $tempUrl['tempUrl'] = \haibao\cms\business\ImageLibrary::getImageUrlById($bdvalue->ImgId);
                    $brandUrlArr[$bdkey]['ImgId'] = self::getImageLink($tempUrl['tempUrl'][$bdvalue->ImgId],60,60);
                } 
            }
        }
        
        foreach ($designerList as $key => $value){
            $designerInfoList[$key]['Id'] = $value['Id'];
            $designerInfoList[$key]['topic_Id'] = $value['TopicId'];
            $designerInfoList[$key]['NameCN'] = $value['NameCN'];
            $designerInfoList[$key]['NameEN'] = $value['NameEN'];
            $designerInfoList[$key]['IsBrand'] = $value['IsBrand'];
            if($value['ImgId']){
                $tempUrl['tempUrl'] = \haibao\cms\business\ImageLibrary::getImageUrlById($value['ImgId']);
                $designerInfoList[$key]['ImgUrl'] = self::getImageLink($tempUrl['tempUrl'][$value['ImgId']],160,160);
            }else{
                $designerInfoList[$key]['ImgUrl'] = '';
            }
            
            $designerInfoList[$key]['RelBrand'] = '';
            
            if(isset($brandUrlArr[$value['BrandId']]) && $brandUrlArr[$value['BrandId']]){
                $designerInfoList[$key]['RelBrand'] = '';
                $designerInfoList[$key]['RelBrandUrl'] = $bransdHost.'/brand/'.$brandUrlArr[$value['BrandId']]['BrandUrl'].'/';
                $designerInfoList[$key]['RelBrandImgUrl'] = $brandUrlArr[$value['BrandId']]['ImgId'];
            }else{
                if($value['IsBrand']){
                    $designerInfoList[$key]['RelBrand'] = '成就高于品牌';
                    $designerInfoList[$key]['RelBrandUrl'] = '';
                    $designerInfoList[$key]['RelBrandImgUrl'] ='';
                }else{
                    $designerInfoList[$key]['RelBrand'] = '';
                    $designerInfoList[$key]['RelBrandUrl'] = '';
                    $designerInfoList[$key]['RelBrandImgUrl'] ='';
                }
            }
            
        }
        return $designerInfoList;
     
     }
     
     /**
      *
      * @param int $type
      * 类型 1:品牌, 2:明星
      */
     private function getAreaAndPosition($type=1){
         $data=array();
         $brandBusiness = new BrandBusiness();
         if($type==1){
             $data['Region'] = \haibao\cms\business\Brand::$brandProperty;
             $data['Place'] = \haibao\cms\business\Brand::$brandRegion;
         }else{
             $data['Region'] = \haibao\cms\business\Celebrity::$celebrityCategory;
             $data['Place'] = \haibao\cms\business\Celebrity::$celebrityArea;
         }
         return $data;
     }
     
     private function getStarOrBrandArticle($param){
         $data = array();
         $result= array();
         $articleControl = ArticleController::initArticleControl();
         $queryCondition['relType'] = $param['relType'];//1为品牌，2为明星
         $queryCondition['limit'] = $param['limit'];
         $queryCondition['isProImage'] = 1; //是否有导读图
         $queryCondition['proImageLevel'] = $param['proImageLevel'];//为400*400
         $queryCondition['source'] = __CLASS__;
         $queryCondition['isTag'] = 1;//是否有标签
         $queryCondition['tagType'] = $param['tagType'];//0为normal,1为品牌,2为产品,3为组合,4为明星
         $this->getArticleControl(3,$queryCondition);
         $result = $articleControl->getChannelArticleToBrandOrStar();
     
         //为了前台样式能确定第几个关系数组
         foreach($result as $key => $value){
             $data[] = $result[$key];
         }
         return $data;
     }
     
 }